<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>站点信息配置</span>
        </div>
      </template>

      <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" class="site-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="站点标题" prop="siteTitle">
              <el-input v-model="formData.siteTitle" placeholder="请输入站点标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="站点副标题" prop="siteSubtitle">
              <el-input v-model="formData.siteSubtitle" placeholder="请输入站点副标题" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="站点域名" prop="siteDomain">
              <el-input v-model="formData.siteDomain" placeholder="请输入站点域名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="站点LOGO" prop="siteLogoUrl">
              <ImageSelector type="img" v-model:imgUrl="formData.siteLogoUrl" :preview-src-list="[formData.siteLogoUrl]" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="站点Icon" prop="icon">
              <ImageSelector type="img" v-model:imgUrl="formData.icon" :preview-src-list="[formData.icon]" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="站点关键字" prop="siteKeywords">
              <el-input v-model="formData.siteKeywords" placeholder="请输入站点关键字" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="默认语言" prop="defaultLanguage">
              <el-input v-model="formData.defaultLanguage" placeholder="请输入默认语言" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="站点模板" prop="siteTemplate">
              <el-select v-model="formData.siteTemplate" placeholder="请选择站点模板" style="width: 100%">
                <el-option label="默认模板" value="default" />
                <el-option label="模板V1" value="v1" />
                <el-option label="模板V2" value="v2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="站点备案" prop="siteRecord">
              <el-input v-model="formData.siteRecord" placeholder="请输入站点备案信息" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="站点描述" prop="siteDescription">
          <el-input v-model="formData.siteDescription" type="textarea" :rows="3" placeholder="请输入站点描述" />
        </el-form-item>

        <el-form-item label="尾部信息" prop="footerInfo">
          <el-input v-model="formData.footerInfo" type="textarea" :rows="3" placeholder="请输入尾部信息" />
        </el-form-item>
        <el-form-item label="拓展代码" prop="extendCode">
          <el-input v-model="formData.extendCode" type="textarea" :rows="3" placeholder="请输入拓展代码" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            {{ isEdit ? "更新" : "保存" }}
          </el-button>
          <el-button @click="$router.back()">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from "element-plus";
import { getSiteInfo, createSiteInfo, updateSiteInfo } from "@/api/common";
import { useRouter } from "vue-router";
// @ts-ignore
import ImageSelector from "@/components/ImageSelector/index.vue";

// 表单引用
const formRef = ref<FormInstance>();

// 加载状态
const loading = ref(false);

// 是否为编辑模式
const isEdit = ref(false);

const router = useRouter();
// 表单数据
const formData = reactive({
  _id: "",
  siteTitle: "",
  siteSubtitle: "",
  siteDomain: "",
  siteLogoUrl: "",
  icon: "",
  siteKeywords: "",
  siteDescription: "",
  siteRecord: "",
  siteTemplate: "default" as "default" | "v1" | "v2",
  footerInfo: "",
  defaultLanguage: "",
  extendCode: ""
});

// 表单验证规则
const rules: FormRules = {
  siteTitle: [{ required: true, message: "站点标题不能为空", trigger: "blur" }],
  siteDomain: [{ required: true, message: "站点域名不能为空", trigger: "blur" }]
};

/**
 * 获取站点信息数据
 * 从接口获取已配置的站点信息
 */
const fetchSiteInfo = async () => {
  try {
    const res = await getSiteInfo();
    console.log(res, "res");

    if (res.data && res.data._id) {
      // 有数据，编辑模式
      isEdit.value = true;
      Object.assign(formData, res.data);
    } else {
      // 无数据，新增模式
      isEdit.value = false;
    }
  } catch (error) {
    console.error("获取站点信息失败:", error);
    ElMessage.error("获取站点信息失败");
  }
};

/**
 * 提交表单数据
 * 根据是否有_id判断调用新增或更新接口
 */
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    loading.value = true;

    if (isEdit.value && formData._id) {
      // 更新站点信息 - 去除_id字段
      const { _id, ...updateData } = formData;
      await updateSiteInfo(_id, updateData);
      ElMessage.success("站点信息更新成功");
    } else {
      // 创建站点信息，不传递_id字段
      const { _id, ...createData } = formData;
      const res = await createSiteInfo(createData);
      if (res.data && res.data._id) {
        formData._id = res.data._id;
        isEdit.value = true;
      }
      ElMessage.success("站点信息保存成功");
    }
  } catch (error) {
    console.error("保存站点信息失败:", error);
    ElMessage.error("保存站点信息失败");
  } finally {
    loading.value = false;
  }
};

/**
 * 重置表单数据
 * 清空所有表单字段
 */
const handleReset = () => {
  ElMessageBox.confirm("确定要重置表单吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    if (formRef.value) {
      formRef.value.resetFields();
    }
    // 重置为默认值
    Object.assign(formData, {
      _id: "",
      siteTitle: "",
      siteSubtitle: "",
      siteDomain: "",
      siteLogoUrl: "",
      icon: "",
      siteKeywords: "",
      siteDescription: "",
      siteRecord: "",
      siteTemplate: "default",
      footerInfo: "",
      defaultLanguage: ""
    });
    isEdit.value = false;
    ElMessage.success("表单已重置");
  });
};

// 页面挂载时获取数据
onMounted(() => {
  fetchSiteInfo();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.box-card {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}

.site-form {
  padding: 20px 0;
}

.el-form-item {
  margin-bottom: 24px;
}

.el-textarea {
  width: 100%;
}
</style>
